
package com.yimixian.app.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;
import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.cart.GoodsItemPresenter;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.fragment.HomeFragment;
import com.yimixian.app.goods.GoodDetailActivity;
import com.yimixian.app.goods.GoodDetailTopFragment;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import com.ymx.sdk.util.DensityUtils;
import com.ymx.sdk.util.DeviceUtils;

import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by zhilian-2 on 2015/10/27.
 */
public class HomeItemView extends LinearLayout {

    @InjectView(R.id.lin_top_money)
    LinearLayout linTopMoney;
    @InjectView(R.id.real_money_top)
    TextView realMoneyTop;
    @InjectView(R.id.lin_bottom_money)
    LinearLayout linBottomMoney;
    @InjectView(R.id.image_view)
    ImageView imageView;
    @InjectView(R.id.title)
    TextView mTitleText;
    @InjectView(R.id.once_count)
    TextView onceCount;
    @InjectView(R.id.left_count)
    TextView leftCount;
    @InjectView(R.id.count_down)
    TextView countDown;
    @InjectView(R.id.start_sale)
    TextView startSale;
    @InjectView(R.id.real_money)
    TextView realMoney;
    @InjectView(R.id.old_money)
    TextView oldMoney;
    @InjectView(R.id.control_area)
    FrameLayout mControlArea;
    @InjectView(R.id.tuan_button)
    TextView mTuanButton;
    @InjectView(R.id.control_tuan_area)
    FrameLayout mControlTuanArea;
    @InjectView(R.id.list_item)
    LinearLayout listItem;
    @InjectView(R.id.promotion_image)
    ImageView mPromotionImage;
    @InjectView(R.id.bottom_one)
    LinearLayout mBottomOne;
    @InjectView(R.id.old_rmb)
    TextView mOldRmb;
    @InjectView(R.id.real_rmb)
    TextView mRealRmb;

    private GoodsItem mGoodsItem;
    private DataManager mDataManager;
    private int mScreenWidth;
    private GoodsItemPresenter.OnPlusButtonClickListener mOnPlusButtonClickListener;
    private PlusMinusIcon mPlusMinusIcon;
    private Context mContext;
    private Target target;
    private boolean isFromCouDanPage;
    private float density;
    private boolean is230Init = false;
    private boolean isInited = false;

    public HomeItemView(Context context) {
        super(context);
        initView(context);
    }

    public HomeItemView(Context context, boolean is230Init) {
        super(context);
        this.is230Init = is230Init;
        initView(context);
    }

    public HomeItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public HomeItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        this.mContext = context;
        LayoutInflater.from(getContext()).inflate(R.layout.home_list_item_child, this);
        ButterKnife.inject(this);
        DensityUtils.dp2px(getContext(), 15.0f);
        mScreenWidth = DeviceUtils.getScreenWidth(getContext());
        mDataManager = DataManager.getInstance();
        density = getResources().getDisplayMetrics().density;
    }

    public void setOnPlusButtonClickListener(GoodsItemPresenter.OnPlusButtonClickListener listener) {
        mOnPlusButtonClickListener = listener;
    }

    public void bindData(final GoodsItem goodsItem, String type) {
        bindData(goodsItem, type, false, true);
    }

    public void bindData(final GoodsItem goodsItem, String type, boolean is230Init, boolean showOldPrice) {
        if (goodsItem == null) {
            setVisibility(View.INVISIBLE);
            mGoodsItem = null;
            return;
        }

        if (goodsItem.id == 0) {
            setVisibility(View.INVISIBLE);
            return;
        } else {
            setVisibility(View.VISIBLE);
        }
        int count = 0;
        if (CartManager.getInstance().mCartGoodsItems != null && goodsItem != null) {
            count = CartManager.getInstance().mCartGoodsItems.get(goodsItem.id) == null ? 0
                    : Integer
                            .parseInt(CartManager.getInstance().mCartGoodsItems.get(goodsItem.id).count);
        }


        if (mPlusMinusIcon == null) {
            mPlusMinusIcon = new PlusMinusIcon(SystemFramework.getInstance().getGlobalContext(),
                    goodsItem, type,
                    linTopMoney, linBottomMoney, showOldPrice);
            mControlArea.addView(mPlusMinusIcon);
            mPlusMinusIcon.setQuantity(count);
            mPlusMinusIcon.setOnPlusButtonClickListener(mOnPlusButtonClickListener);
        } else {
            mPlusMinusIcon.updateGoodsItem(goodsItem);
            mPlusMinusIcon.setQuantity(count);
        }


        //2.3.0首界面微调
        if(is230Init){
            int screenWidth = getResources().getDisplayMetrics().widthPixels;
            int eachWidth = (DeviceUtils.getScreenWidth(getContext()) - DensityUtils.dp2px(getContext(), 5 * 2 + 7 * 2)) / 3;
            int height = (int) (eachWidth / (goodsItem.imgRatio == 0 ? 1 : goodsItem.imgRatio));
            imageView.getLayoutParams().height = height;
            mPlusMinusIcon.mPlusButton.getLayoutParams().width = (int) (density * 30);
            mPlusMinusIcon.mPlusButton.getLayoutParams().height = (int) (density * 30);
            mPlusMinusIcon.mMinusButton.getLayoutParams().width = (int) (density * 30);
            mPlusMinusIcon.mMinusButton.getLayoutParams().height = (int) (density * 30);
            LinearLayout pL = (LinearLayout) mPlusMinusIcon.mPlusButton.getParent();
            RelativeLayout.LayoutParams pLLayoutParams = (RelativeLayout.LayoutParams) pL.getLayoutParams();
            pLLayoutParams.setMargins(0, 0, (int) (0 * density), 0);
            mPlusMinusIcon.mQuantityText.setTextSize(16);
            mTuanButton.getLayoutParams().width = FrameLayout.LayoutParams.WRAP_CONTENT;
            mTuanButton.getLayoutParams().height = FrameLayout.LayoutParams.WRAP_CONTENT;
            mTuanButton.setPadding((int) (3 * density), (int) (3 * density), (int) (3 * density), (int) (3 * density));
            FrameLayout parent = (FrameLayout) mTuanButton.getParent();
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) parent.getLayoutParams();
            lp.setMargins(lp.leftMargin, lp.topMargin, (int) (5 * density), lp.bottomMargin);
            mOldRmb.setTextSize(10);
            mRealRmb.setTextSize(11);
            oldMoney.setTextSize(11);
            realMoney.setTextSize(17);
        }else{
            int width = DeviceUtils.getScreenWidth(getContext()) / 2
                    - DensityUtils.dp2px(getContext(), 15.0f);
            int height = (int) (width / (goodsItem.imgRatio == 0 ? 1 : goodsItem.imgRatio));
            imageView.getLayoutParams().height = height;
        }

        if(!CartManager.getInstance().isUserLogin()){
            int tempCount = CartManager.getInstance().getOfflineGoodCount(goodsItem.id);
            if(tempCount!=-1){
                count = tempCount;
            }
        }
        linTopMoney.setVisibility(count > 0 ? View.VISIBLE : View.GONE);
        linBottomMoney.setVisibility(count > 0 ? View.INVISIBLE : View.VISIBLE);

        mGoodsItem = goodsItem;

        String imgUrl = mDataManager.getImageUrl(goodsItem.img, mScreenWidth / 4);
        Picasso picasso = Picasso.with(getContext());
        picasso.load(imgUrl).placeholder(R.drawable.icon_home_item_default).into(imageView);
        //保存切圆动画图片
        if(target == null){
            target = new Target() {
                @Override
                public void onBitmapLoaded(Bitmap back, Picasso.LoadedFrom from) {
                    int width = back.getWidth();
                    int height = back.getHeight();
                    float radius = width > height ? height / 2 : width / 2;
                    float centerX = width / 2;
                    float centerY = height / 2;
                    Bitmap bm_circle = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                    Canvas canvas_circle = new Canvas(bm_circle);
                    Paint paint = new Paint();
                    paint.setAntiAlias(true);
                    canvas_circle.drawCircle(centerX, centerY, radius, paint);
                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                    canvas_circle.drawBitmap(back, 0, 0, paint);
                    Matrix matrix = new Matrix();
                    float temp = mContext.getResources().getDisplayMetrics().density * 40;
                    matrix.setScale(temp / width, temp / height);
                    mPlusMinusIcon.setShowBack(Bitmap.createBitmap(bm_circle, 0, 0, width, height, matrix, false));
                    bm_circle.recycle();
                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {}

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {}
            };
        }
        picasso.load(imgUrl).into(target);

        if (Strings.isNullOrEmpty(mGoodsItem.promotionImg)) {
            mPromotionImage.setVisibility(GONE);
        } else {
            mPromotionImage.setVisibility(VISIBLE);
            int size = getResources().getDimensionPixelSize(R.dimen.promotion_image_size2);
            picasso.load(mDataManager.getImageUrl(mGoodsItem.promotionImg, size)).into(
                    mPromotionImage);
        }

        // 判断是否为团购商品
        if (goodsItem.isBuyingGroup == 1) {
            mControlArea.setVisibility(GONE);
            mControlTuanArea.setVisibility(View.VISIBLE);
            if (goodsItem.shouldBuyCount < 1) {
                mTuanButton.setBackgroundResource(R.drawable.rounded_button_disabled);
                mTuanButton.setEnabled(true);
            } else {
                mTuanButton.setBackgroundResource(R.drawable.orange_button_bg);
                mTuanButton.setEnabled(true);
            }
            if(getContext() instanceof YMXMainActivity){
                mControlTuanArea.setPadding(0, (int) (density * 5), 0, 0);
            }
        } else {
            mControlTuanArea.setVisibility(GONE);
            mControlArea.setVisibility(View.VISIBLE);
        }

        mTuanButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startTuan(goodsItem);
            }
        });

        mTitleText.setText(goodsItem.name);

        String buyingGroupCount = goodsItem.isBuyingGroup == 1 ? goodsItem.buyingGroupCount
                + "人团  " : "";
        if (goodsItem.isBuyingGroup == 1) {
            onceCount.setText(buyingGroupCount + "  " +
                    (StringUtils.isEmpty(goodsItem.unitDesc) ? "" : goodsItem.unitDesc));
        } else {
            onceCount.setText(StringUtils.isEmpty(goodsItem.unitDesc) ? "" : goodsItem.unitDesc);
        }
        // onceCount.setText(StringUtils.isEmpty(goodsItem.unitDesc) ? "" :
        // goodsItem.unitDesc);
        leftCount.setText(StringUtils.isEmpty(goodsItem.stockCount) ? "" : goodsItem.stockCount);
        // startSale.setText(StringUtils.isEmpty(goodsItem.saleStatus) ? "" :
        // goodsItem.saleStatus);
        if (StringUtils.isEmpty(goodsItem.saleStatus)) {
            countDown.setVisibility(GONE);
        } else {
            countDown.setVisibility(VISIBLE);
            countDown.setText(goodsItem.saleStatus);
        }
        realMoney.setText(StringUtils.isEmpty(goodsItem.unitPrice) ? "" : goodsItem.unitPrice);
        if (TextUtils.isEmpty(goodsItem.unitOldPrice)) {
            oldMoney.setVisibility(View.INVISIBLE);
            mOldRmb.setVisibility(View.INVISIBLE);
        } else {
            oldMoney.setVisibility(View.VISIBLE);
            mOldRmb.setVisibility(View.VISIBLE);

        }

        if(!showOldPrice){
            oldMoney.setVisibility(View.INVISIBLE);
            mOldRmb.setVisibility(View.INVISIBLE);
        }

        oldMoney.setText(StringUtils.isEmpty(goodsItem.unitOldPrice) ? "" : goodsItem.unitOldPrice);
        oldMoney.setPaintFlags(oldMoney.getPaintFlags()
                | Paint.STRIKE_THRU_TEXT_FLAG);
        realMoneyTop.setText(StringUtils.isEmpty(goodsItem.unitPrice) ? "" : goodsItem.unitPrice);
        // String buyingGroupCount = goodsItem.isBuyingGroup == 1 ?
        // goodsItem.buyingGroupCount + "人团  " : "";
        // mStatusText.setText(buyingGroupCount +
        // Strings.nullToEmpty(goodsItem.saleStatus) + "  " +
        // goodsItem.unitDesc);

        // builder.setSpan(new RelativeSizeSpan(.686f), 0, 1,
        // Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        // mPriceText.setText(builder);
        // mOriginalPriceText.setText(goodsItem.unitOldPrice);
        if (!Strings.isNullOrEmpty(goodsItem.descUrl)) {
            listItem.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (goodsItem.isBuyingGroup == 0) {
                        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                                StatConstants.HOME_GOOD_ITEM_IMAGE_CLICK);
                        String flag = "";
                        if(isFromCouDanPage)
                            flag = "1";
                        ((Activity)getContext()).startActivityForResult(
                                GoodDetailActivity.buildIntent(getContext(),
                                        String.valueOf(goodsItem.id)).putExtra("isFromCouDanPage", flag), GoodDetailTopFragment.RETURN_TO_CATEGORY);
                    } else {
                        startTuan(goodsItem);
                    }

                }
            });
        } else {
            listItem.setOnClickListener(null);
        }

    }

    private void startTuan(GoodsItem goodsItem) {
        if (goodsItem != null) {
            if (goodsItem.shouldBuyCount > 0) {
                startTuanWebActivity(goodsItem);
            } else {
                if (!TextUtils.isEmpty(goodsItem.countZeroReason)
                    ) {UiUtils.showToast(goodsItem.countZeroReason);
                    return;
                }
            }
        }
    }

    private void startTuanWebActivity(GoodsItem goodsItem) {
        Intent intent = new Intent(getContext(), WebViewActivity.class);
        intent.putExtra(WebViewActivity.EXTRA_URL, goodsItem.descUrl);
        getContext().startActivity(intent);
    }

    public void setIsFromCouDanPage(boolean isFromCouDanPage) {
        this.isFromCouDanPage = isFromCouDanPage;
    }

}
